<?php
declare (strict_types=1);

namespace app\admin\model\media;

use app\admin\model\BaseModel;

class Module extends BaseModel
{
    //当前模型对应的数据表名称
    protected $name = 'media_module';

    public function getList($filter = []): array
    {
        $where = function ($query) use ($filter) {
            if (isset($filter['group_id'])) {
                $query->where('group_id', '=', $filter['group_id']);
            }
            if (isset($filter['website_id'])) {
                $query->where('website_id', '=', $filter['website_id']);
            }
            if (isset($filter['name'])) {
                $query->where('name', 'like', '%' . $filter['name'] . '%');
            }
            if (isset($filter['url'])) {
                $query->where('url', 'like', '%' . $filter['url'] . '%');
            }
            if (isset($filter['status'])) {
                $query->where('status', '=', $filter['status']);
            }
        };
        $order = ['weigh' => 'desc', 'id' => 'asc'];
        return self::getPageList($where, $order);
    }

    public function getPageList($where = [], $order = [], $page = 0, $limit = 0)
    {
        $page = $page ?: request()->param("page", 1, 'intval');
        $limit = $limit ?: request()->param("limit", 10, 'intval');

        $total = self::
        where($where)
            ->count();

        $list = self::with(['group', 'website'])
            ->where($where)
            ->order($order)
            ->page($page, $limit)
            ->select();

        return [$total, $list];
    }

    public function group()
    {
        return $this->belongsTo('Group', 'group_id', 'id')->field('id,name');
    }

    public function website()
    {
        return $this->belongsTo('Website', 'website_id', 'id')->field('id,name');
    }

}